package edu.umd.mhealth.oauth;



import org.scribe.builder.ServiceBuilder;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Execute the OAuthRequestTokenTask to retrieve the request, and authorize the request.
 * After the request is authorized by the user, the callback URL will be intercepted here.
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class OAuthAccessTokenActivity extends Activity {
	private static String apiKey;
	private static String apiSecret;
	private static String callback;
	private static String authUrl;
	private static Token accessToken;
	private static Token requestToken;
	private static OAuthService service;
	private WebView  webview;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Log.d("in Oauth", "in Oauth");
		
        webview = new WebView(this);
        webview.getSettings().setJavaScriptEnabled(true);  
        webview.setVisibility(View.VISIBLE);
        setContentView(webview);
        
        Bundle extras = getIntent().getExtras();
        authUrl = extras.getString("authUrl");
        apiKey = extras.getString("apiKey");
        apiSecret = extras.getString("apiSecret");
        callback = extras.getString("callback");
        
        service = new ServiceBuilder()  // OAuth settings for fitbit
    	.provider(FitbitApi.class)
    	.apiKey(apiKey) 
    	.apiSecret(apiSecret) 
    	.callback(callback) 
    	.debug() 
    	.build();
        
        
        webview.setWebViewClient(new WebViewClient() {  
        	@Override  
            public void onPageStarted(WebView view, String url,Bitmap bitmap)  {  
        		Log.d("in started", url);
        		if(url.startsWith("http://www.fitbit.com/activity_main")){
        			Log.d("in started if stmt" +
        					"", url);
        			new ProcessToken(url).execute();
        		}
            }
        });  
        
        Log.d("right before execute", "right before execute");
        new LoginTask().execute();
	}
	

	/* Performs an OAuth authentication and receive access token for further 
	 * GET and POST requests */
	private class LoginTask extends AsyncTask<Void, Void, Void>{	
		@Override
		protected Void doInBackground(Void... params) {
			requestToken = service.getRequestToken();
			authUrl = service.getAuthorizationUrl(requestToken);
			return null;
		}
		
		protected void onPostExecute(Void result){
	        webview.loadUrl(authUrl);	
		}
		
	}
	
	private class ProcessToken extends AsyncTask<Void, Void, String> {
		String url;
		
		public ProcessToken(String url) {
			this.url=url;
		}
		
		@Override
		protected String doInBackground(Void...params) {
			String authCode = "error";
			
			if (url.startsWith("http://www.fitbit.com")) {				
        		try {
        			if (url.contains("oauth_verifier")) {
        				Uri uri = Uri.parse(url);	//extracting authorization code from url 
        				authCode = uri.getQueryParameter("oauth_verifier"); ;	
        				Verifier verifier = new Verifier(authCode);   // getting access token
        				accessToken  = service.getAccessToken(requestToken, verifier);
        			}
				} catch (Exception e) {
					e.printStackTrace();
				}
        	} 
            return authCode;
		}


		@Override
		protected void onPostExecute(String authCode) {
			Intent i = getIntent().putExtra("accessToken", accessToken).putExtra("requestToken", requestToken);
			
			if(getParent() == null){
				setResult(Activity.RESULT_OK, i);
			} else {
				getParent().setResult(Activity.RESULT_OK, i);
			}
			
			finish();
		}
	}
}
